/*
* This file is a part of the open-eBackup project.
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* Copyright (c) [2024] Huawei Technologies Co.,Ltd.
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*/
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { ModalRef } from '@iux/live';
import {
  CopiesService,
  ProtectedResourceApiService
} from 'app/shared/api/services';
import { DataMap } from 'app/shared/consts';
import { BaseUtilService } from 'app/shared/services';
import { AppUtilsService } from 'app/shared/services/app-utils.service';
import { each, find, isEmpty } from 'lodash';
import { Observable } from 'rxjs';

@Component({
  selector: 'aui-index-with-agent',
  templateUrl: './index-with-agent.component.html',
  styleUrls: ['./index-with-agent.component.less']
})
export class IndexWithAgentComponent implements OnInit {
  rowData;
  formGroup: FormGroup;
  agentOptions = [];

  constructor(
    private modal: ModalRef,
    private fb: FormBuilder,
    private copiesApiService: CopiesService,
    private appUtilsService: AppUtilsService,
    private baseUtilService: BaseUtilService,
    private protectedResourceApiService: ProtectedResourceApiService
  ) {}

  ngOnInit(): void {
    this.initForm();
    this.getAgents();
  }

  initForm() {
    this.formGroup = this.fb.group({
      agents: new FormControl('', {
        validators: [this.baseUtilService.VALID.required()]
      })
    });
    this.formGroup.statusChanges.subscribe(() => this.disableOkBtn());
  }

  disableOkBtn() {
    this.modal.getInstance().lvOkDisabled = this.formGroup.invalid;
  }

  getAgents() {
    const extParams = {
      conditions: JSON.stringify({
        subType: ['VolumePlugin']
      })
    };
    const resourceProperties = JSON.parse(
      this.rowData?.resource_properties || '{}'
    );
    const originAgent = resourceProperties?.environment_uuid;
    this.appUtilsService.getResourceByRecursion(
      extParams,
      params => this.protectedResourceApiService.ListResources(params),
      resource => {
        const hostArr = [];
        each(resource, item => {
          if (
            item.environment?.linkStatus ===
              DataMap.resource_LinkStatus_Special.normal.value &&
            item.environment?.osType ===
              resourceProperties?.environment_os_type &&
            item.environment?.extendInfo?.scenario ===
              DataMap.proxyHostType.external.value
          ) {
            hostArr.push({
              ...item,
              key: item.environment.uuid,
              value: item.environment.uuid,
              label: !isEmpty(item.environment?.endpoint)
                ? `${item.environment?.name}(${item.environment?.endpoint})`
                : item.environment?.name,
              isLeaf: true
            });
          }
        });
        this.agentOptions = hostArr;
        if (find(this.agentOptions, item => item.value === originAgent)) {
          this.formGroup.get('agents').setValue(originAgent);
        }
      }
    );
  }

  onOk(): Observable<any> {
    return this.copiesApiService.createCopyIndexV1CopiesCopyIdActionCreateIndexPost(
      {
        copyId: this.rowData?.uuid,
        agents: this.formGroup.get('agents').value
      }
    );
  }
}
